<?php


namespace App\Service\Cooperative;


use App\Constants\ErrorCode;
use App\Constants\Model\User;
use App\Constants\Model\UserEmployer;
use App\Dao\CertificationIdcardDao;
use App\Dao\UserDao;
use App\Dao\UserEmployerDao;
use App\Exception\BusinessException;
use App\Utils\Log;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use function EasyWeChat\Kernel\Support\str_random;

class UserEmployerService extends BaseService
{
    /**
     * @Inject()
     * @var UserEmployerDao
     */
    protected $userEmployerDao;

    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;

    /**
     * @Inject()
     * @var CertificationIdcardDao
     */
    protected $certificationIdCardDao;

    /**
     * @param array $where
     * @return array
     */
    public function index(array $where):array
    {
        $pageInfo = $this->extractPaginateInfo($where);
        $where['cooperative_id'] = $this->user()->cooperative_id;
        $index = $this
            ->userEmployerDao
            ->where($where)
            ->withCount('tasks')
            ->with('user')
            ->paginate(
                $pageInfo['perPage'],['*'],'page',$pageInfo['page']
            );
        return $this->formatIndex($index);
    }

    public function formatIndex(\Hyperf\Contract\LengthAwarePaginatorInterface $index)
    {
        $data = [];
        /** @var \App\Model\UserEmployer $userEmployer */
        foreach ($index->items() as $userEmployer) {
            $data[] = [
                'id' => $userEmployer->id,
                'employer_user_avatar' => $userEmployer->user->avatar,
                'employer_user_name' => $userEmployer->user->nickname,
                'employer_phone' => $userEmployer->user->phone,
                'employer_balance' => $userEmployer->balance,
                'employer_credit_point' => $userEmployer->credit_point,
                'tasks_count' => $userEmployer->tasks_count,
                'created_at' => $userEmployer->created_at->toDatetimeString()
            ];
        }

        return [
            'data' => $data,
            'current_page' => $index->currentPage(),
            'total' => $index->total(),
            'per_page' => $index->perPage()
        ];
    }

    /**
     * @param int $userEmployerId
     * @return bool
     */
    public function block(int $userEmployerId): bool
    {
        $userEmployer = $this->userEmployerDao->firstOrFail(['id' => $userEmployerId,'cooperative_id'=>$this->user()->cooperative_id]);

        // TODO 这里要写操作日志
        if (UserEmployer::STATUS_BLOCKED == $userEmployer->status) {
            throw new BusinessException(ErrorCode::USER_EMPLOYER_HAS_BEEN_BLOCKED);
        }

        $userEmployer->status = UserEmployer::STATUS_BLOCKED;
        return $userEmployer->save();
    }

    /**
     * @param int $userEmployerId
     * @return bool
     */
    public function unblock(int $userEmployerId): bool
    {
        $userEmployer = $this->userEmployerDao->firstOrFail(['id' => $userEmployerId,'cooperative_id'=>$this->user()->cooperative_id]);

        // TODO 这里要写操作日志
        if (UserEmployer::STATUS_UNBLOCK == $userEmployer->status) {
            throw new BusinessException(ErrorCode::USER_EMPLOYER_HAS_BEEN_UNBLOCKED);
        }

        $userEmployer->status = UserEmployer::STATUS_UNBLOCK;
        return $userEmployer->save();
    }

    /**
     * @param int $userEmployerId
     * @param float $balance
     * @return \App\Model\UserEmployer
     */
    public function setBalance(int $userEmployerId, float $balance): \App\Model\UserEmployer
    {
        // TODO 这里要写操作日志
        $userEmployer = $this->userEmployerDao->firstOrFail(['id' => $userEmployerId,'cooperative_id'=>$this->user()->cooperative_id]);

        $userEmployer->balance = $balance;

        $userEmployer->save();

        return $userEmployer;
    }

    /**
     * @param array $data
     * @return \App\Model\UserEmployer
     * @throws \Exception
     */
    public function create(array $data):\App\Model\UserEmployer
    {
        Db::beginTransaction();
        try {
            //创建用户数据
            $user = $this->userDao->create([
                'cooperative_id' => $this->user()->cooperative_id,
                'phone' => $data['phone'],
                'password' => password_hash($data['password'],PASSWORD_BCRYPT),
                'status' => User::STATUS_UNBLOCK,
                'is_employer' => User::IS_EMPLOYER_YES,
                'credit_point' => User::DEFAULT_CREDIT_POINT,
                'level' => User::DEFAULT_LEVEL,
                'nickname' => str_random(6)
            ]);

            // 设置用户头像
            if (isset($data['avatar']) && $data['avatar']) {
                $user->avatar = $data['avatar'];
            }

            if (isset($data['idcard']) && $data['idcard'] && isset($data['name']) && $data['name']) {
                //创建个人认证信息
                $this->certificationIdCardDao->create([
                    'idcard' => $data['idcard'],
                    'name' => $data['name'],
                ]);
                $user->personal_certification = User::PERSONAL_CERTIFICATION_YES;
            }

            //创建悬赏主数据
            $userEmployer = $this->userEmployerDao->create([
                'user_id' => $user->id,
                'cooperative_id' => $this->user()->cooperative_id,
                'status' => UserEmployer::STATUS_UNBLOCK,
                'credit_point' => UserEmployer::DEFAULT_CREDIT_POINT,
                'shop_point' => UserEmployer::DEFAULT_SHOP_POINT,
            ]);
            $user->save();
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollBack();
            Log::get()->error($exception->getMessage(), $data);
            throw $exception;
        }
        return $userEmployer;
    }
}